import Card from '@/components/Card';
import Description from '@/components/Description';
import { realTimeMonitoringControllerMeterRealtimeData } from '@/services/ess/realTimeMonitoring';
import { Spin } from 'antd';
import type { DescriptionsProps } from 'antd/es/descriptions';
import cls from 'classnames';
import React, { useEffect, useState } from 'react';
import { useIntl } from 'umi';
import { useDeviceInfo, useIsFresh, useSelectedDeviceNode } from '../SelectedDeviceNodeContext';
import Style from './index.less';

export const Info: React.FC = () => {
  const { isRefesh, setIsRefesh } = useIsFresh();
  const deviceNode = useSelectedDeviceNode();
  const { setDeviceInfo } = useDeviceInfo();
  const [loading, setLoading] = useState<boolean>(true);
  const intl = useIntl();
  const RTOverviewCopy = [
    {
      key: 'onlineState',
      label: intl.formatMessage({ id: 'data.onlineStatus' }),
      children: '',
    },
    {
      key: 'gridFreq',
      label: `${intl.formatMessage({ id: 'stationRealtimeMonitoring.gridFrequency' })}`,
      children: '',
    },
    {
      key: 'powerFactor',
      label: intl.formatMessage({ id: 'stationRealtimeMonitoring.powerFactor' }),
      children: '',
    },
    {
      key: 'activePower',
      label: `${intl.formatMessage({ id: 'stationRealtimeMonitoring.totalActivePower' })}`,
      children: '',
    },
    {
      key: 'reactivePower',
      label: `${intl.formatMessage({ id: 'stationRealtimeMonitoring.totalReactivePower' })}`,
      children: '',
    },
    {
      key: 'apparentPower',
      label: `${intl.formatMessage({ id: 'stationRealtimeMonitoring.totalApparentPower' })}`,
      children: '',
    },
    {
      key: 'ia',
      label: `${intl.formatMessage({ id: 'stationRealtimeMonitoring.currentA' })}`,
      children: '',
    },
    {
      key: 'ib',
      label: `${intl.formatMessage({ id: 'stationRealtimeMonitoring.currentB' })}`,
      children: '',
    },
    {
      key: 'ic',
      label: `${intl.formatMessage({ id: 'stationRealtimeMonitoring.currentC' })}`,
      children: '',
    },
    {
      key: 'ua',
      label: intl.formatMessage({ id: 'stationRealtimeMonitoring.voltageA' }),
      children: '',
    },
    {
      key: 'ub',
      label: intl.formatMessage({ id: 'stationRealtimeMonitoring.voltageB' }),
      children: '',
    },
    {
      key: 'uc',
      label: intl.formatMessage({ id: 'stationRealtimeMonitoring.voltageC' }),
      children: '',
    },
  ];

  const energyDataCopy = [
    {
      key: 'combinedActiveTotal',
      label: `${intl.formatMessage({
        id: 'stationRealtimeMonitoring.combinedActiveTotalEnergy',
      })}`,
      children: '',
    },
    {
      key: 'combinedActiveTip',
      label: `${intl.formatMessage({
        id: 'stationRealtimeMonitoring.combinedActiveSharpEnergy',
      })}`, // '组合有功尖电能(kWh)'
      children: '',
    },
    {
      key: 'combinedActivePeak',
      label: `${intl.formatMessage({
        id: 'stationRealtimeMonitoring.combinedActivePeakEnergy',
      })}`, // '组合有功峰电能(kWh)'
      children: '',
    },
    {
      key: 'combinedActiveFlat',
      label: `${intl.formatMessage({
        id: 'stationRealtimeMonitoring.combinedActiveShoulderEnergy',
      })}`, // '组合有功平电能(kWh)'
      children: '',
    },
    {
      key: 'combinedActiveValley',
      label: `${intl.formatMessage({
        id: 'stationRealtimeMonitoring.combinedActiveOffPeakEnergy',
      })}`, // '组合有功谷电能(kWh)'
      children: '',
    },
    {
      key: 'positiveActiveTotal',
      label: `${intl.formatMessage({
        id: 'stationRealtimeMonitoring.positiveActiveTotalEnergy',
      })}`, // '正向有功总电能(kWh)'
      children: '',
    },
    {
      key: 'positiveActiveTip',
      label: `${intl.formatMessage({
        id: 'stationRealtimeMonitoring.positiveActiveSharpEnergy',
      })}`, // '正向有功尖电能(kWh)'
      children: '',
    },
    {
      key: 'positiveActivePeak',
      label: `${intl.formatMessage({
        id: 'stationRealtimeMonitoring.positiveActivePeakEnergy',
      })}`, // '正向有功峰电能(kWh)'
      children: '',
    },
    {
      key: 'positiveActiveFlat',
      label: `${intl.formatMessage({
        id: 'stationRealtimeMonitoring.positiveActiveShoulderEnergy',
      })}`, // '正向有功平电能(kWh)'
      children: '',
    },
    {
      key: 'positiveActiveValley',
      label: `${intl.formatMessage({
        id: 'stationRealtimeMonitoring.positiveActiveOffPeakEnergy',
      })}`, // '正向有功谷电能(kWh)'
      children: '',
    },
    {
      key: 'reverseActiveTotal',
      label: `${intl.formatMessage({
        id: 'stationRealtimeMonitoring.reverseActiveTotalEnergy',
      })}`, // '反向有功总电能(kWh)'
      children: '',
    },
    {
      key: 'reverseActiveTip',
      label: `${intl.formatMessage({
        id: 'stationRealtimeMonitoring.reverseActiveSharpEnergy',
      })}`, // '反向有功尖电能(kWh)'
      children: '',
    },
    {
      key: 'reverseActivePeak',
      label: `${intl.formatMessage({
        id: 'stationRealtimeMonitoring.reverseActivePeakEnergy',
      })}`, // '反向有功峰电能(kWh)'
      children: '',
    },
    {
      key: 'reverseActiveFlat',
      label: `${intl.formatMessage({
        id: 'stationRealtimeMonitoring.reverseActiveShoulderEnergy',
      })}`, // '反向有功平电能(kWh)'
      children: '',
    },
    {
      key: 'reverseActiveValley',
      label: `${intl.formatMessage({
        id: 'stationRealtimeMonitoring.reverseActiveOffPeakEnergy',
      })}`, // '反向有功谷电能(kWh)'
      children: '',
    },
    {
      key: 'combinedReactiveTotal',
      label: `${intl.formatMessage({
        id: 'stationRealtimeMonitoring.combinedReactiveTotalEnergy',
      })}`, // '组合无功总电能(kvarh)'
      children: '',
    },
    {
      key: 'combinedReactiveTip',
      label: `${intl.formatMessage({
        id: 'stationRealtimeMonitoring.combinedReactiveSharpEnergy',
      })}`, // '组合无功尖电能(kvarh)'
      children: '',
    },
    {
      key: 'combinedReactivePeak',
      label: `${intl.formatMessage({
        id: 'stationRealtimeMonitoring.combinedReactivePeakEnergy',
      })}`, // '组合无功峰电能(kvarh)'
      children: '',
    },
    {
      key: 'combinedReactiveFlat',
      label: `${intl.formatMessage({
        id: 'stationRealtimeMonitoring.combinedReactiveShoulderEnergy',
      })}`, // '组合无功平电能(kvarh)'
      children: '',
    },
    {
      key: 'combinedReactiveValley',
      label: `${intl.formatMessage({
        id: 'stationRealtimeMonitoring.combinedReactiveOffPeakEnergy',
      })}`, // '组合无功谷电能(kvarh)'
      children: '',
    },
    {
      key: 'positiveReactiveTotal',
      label: `${intl.formatMessage({
        id: 'stationRealtimeMonitoring.positiveReactiveTotalEnergy',
      })}`, // '正向无功总电能(kvarh)'
      children: '',
    },
    {
      key: 'positiveReactiveTip',
      label: `${intl.formatMessage({
        id: 'stationRealtimeMonitoring.positiveReactiveSharpEnergy',
      })}`, // '正向无功尖电能(kvarh)'
      children: '',
    },
    {
      key: 'positiveReactivePeak',
      label: `${intl.formatMessage({
        id: 'stationRealtimeMonitoring.positiveReactivePeakEnergy',
      })}`, // '正向无功峰电能(kvarh)'
      children: '',
    },
    {
      key: 'positiveReactiveFlat',
      label: `${intl.formatMessage({
        id: 'stationRealtimeMonitoring.positiveReactiveShoulderEnergy',
      })}`, // '正向无功平电能(kvarh)'
      children: '',
    },
    {
      key: 'positiveReactiveValley',
      label: `${intl.formatMessage({
        id: 'stationRealtimeMonitoring.positiveReactiveOffPeakEnergy',
      })}`, // '正向无功谷电能(kvarh)'
      children: '',
    },
    {
      key: 'reverseReactiveTotal',
      label: `${intl.formatMessage({
        id: 'stationRealtimeMonitoring.reverseReactiveTotalEnergy',
      })}`, // '反向无功总电能(kvarh)'
      children: '',
    },
    {
      key: 'reverseReactiveTip',
      label: `${intl.formatMessage({
        id: 'stationRealtimeMonitoring.reverseReactiveSharpEnergy',
      })}`, // '反向无功尖电能(kvarh)'
      children: '',
    },
    {
      key: 'reverseReactivePeak',
      label: `${intl.formatMessage({
        id: 'stationRealtimeMonitoring.reverseReactivePeakEnergy',
      })}`, // '反向无功峰电能(kvarh)'
      children: '',
    },
    {
      key: 'reverseReactiveFlat',
      label: `${intl.formatMessage({
        id: 'stationRealtimeMonitoring.reverseReactiveShoulderEnergy',
      })}`, // '反向无功平电能(kvarh)'
      children: '',
    },
    {
      key: 'reverseReactiveValley',
      label: `${intl.formatMessage({
        id: 'stationRealtimeMonitoring.reverseReactiveOffPeakEnergy',
      })}`, // '反向无功谷电能(kvarh)'
      children: '',
    },
  ];

  const [RTOverview, setRTOverview] = useState<DescriptionsProps['items']>(RTOverviewCopy);
  const [energyData, setenergyData] = useState<DescriptionsProps['items']>(energyDataCopy);

  const changeFunction = (key: any, result: any) => {
    if (result === null || result === undefined) {
      return null;
    }

    if (key === 'onlineState') {
      if (result === 1) {
        return intl.formatMessage({ id: 'data.online' });
      } else if (result === 0) {
        return intl.formatMessage({ id: 'data.offline' });
      } else {
        return '--';
      }
    } else {
      return result;
    }
  };

  const changeLoad = (data: API.MeterRealTimeData) => {
    const getRTOverview = RTOverviewCopy.map((item) => {
      return {
        ...item,
        children: changeFunction(item.key, data?.[item.key]),
        hidden: !data?.[item.key],
        label: !data?.[item.key] ? '' : item?.label,
      };
    }).filter((item) => !item.hidden);

    setRTOverview(getRTOverview);

    const getenergyData = energyDataCopy
      .map((item) => {
        return {
          ...item,
          children: data?.[item.key],
        };
      })
      .filter((res) => res.children);
    setenergyData(getenergyData);
  };

  const lebelStyle = {
    width: 180,
  };

  const fetchData = async () => {
    setLoading(true);
    realTimeMonitoringControllerMeterRealtimeData({
      areaId: deviceNode?.areaId?.toString() ?? undefined,
      deviceCode: deviceNode?.deviceCode ?? undefined,
      deviceName: deviceNode?.deviceName ?? undefined,
      deviceType: deviceNode?.deviceType ?? undefined,
    }).then((res) => {
      setDeviceInfo({
        ts: res?.data?.ts ?? undefined,
        onLine:
          res?.data?.onlineState || String(res?.data?.onlineState) === '0'
            ? String(res?.data?.onlineState)
            : undefined,
      });
      setLoading(false);
      changeLoad(res?.data);
    });
  };

  useEffect(() => {
    fetchData();
  }, [deviceNode]);

  useEffect(() => {
    if (isRefesh) {
      console.log('Refreshing change pile data...');
      fetchData();
      setIsRefesh(false);
    }
  }, [isRefesh]);

  return (
    <div>
      <Spin spinning={loading}>
        {/* 基础信息 */}
        <Card
          title={intl.formatMessage({ id: 'stationRealtimeMonitoring.realTime' })}
          className="global-secondary-card"
        >
          <Description
            items={RTOverview}
            column={{ xxl: 3, xl: 3, lg: 3, md: 2, sm: 1 }}
            labelStyle={lebelStyle}
            className={cls(Style.descriptionsImplemente)}
          />
        </Card>
        <Card
          title={intl.formatMessage({ id: 'stationRealtimeMonitoring.energyData' })}
          className="global-secondary-card"
        >
          <div className={Style.energyWrapper}>
            <Description
              items={energyData}
              column={{ xxl: 3, xl: 3, lg: 3, md: 2, sm: 1 }}
              labelStyle={lebelStyle}
              className={cls(Style.descriptionsImplemente)}
            />
          </div>
        </Card>
      </Spin>
    </div>
  );
};
